package com.hengyue.system.repository;

import com.hengyue.common.core.respository.BaseRepository;
import com.hengyue.system.domain.entity.SysMenu;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;


public interface MenuRepository extends BaseRepository<SysMenu, Long> {

    /**
     * 通过 SysUser 的 ID 获取所有的 SysMenu
     *
     * @param userId SysUser 的 ID
     * @return 与该用户关联的所有 SysMenu 列表
     */
    @Query("SELECT DISTINCT m FROM SysMenu m " +
            "JOIN m.roles r " +
            "JOIN r.users u " +
            "WHERE u.id = :userId AND m.menuType IN ('M', 'C') AND m.status = '0'" +
            "ORDER BY m.parentId, m.orderNum")
    List<SysMenu> selectMenusByUserId(@Param("userId") Long userId);

    @Query("SELECT DISTINCT m FROM SysMenu m " +
            "WHERE m.menuType IN ('M', 'C') AND m.status = '0' " +
            "ORDER BY m.parentId, m.orderNum")
    List<SysMenu> selectMenuTreeAll();

    /**
     * 根据用户 ID 查询菜单权限
     *
     * @param userId 用户 ID
     * @return 菜单权限列表
     */
    @Query("SELECT DISTINCT m.perms FROM SysMenu m " +
            "JOIN m.roles r " +
            "JOIN r.users u " +
            "WHERE m.status = '0' AND u.id = :userId")
    List<String> selectMenuPermsByUserId(@Param("userId") Long userId);

    @Query("SELECT m.id FROM SysMenu m JOIN m.roles r WHERE r.id = :roleId")
    List<String> findMenuIdsByRoleId(@Param("roleId") Long roleId);

    boolean existsByNameAndParentIdAndIdNot(String menuName, Long parentId, Long excludeId);

    long countByParentId(Long parentId);

    @Query("SELECT COUNT(r) FROM SysRole r JOIN r.menus m WHERE m.id = :menuId")
    long countRolesByMenuId(@Param("menuId") Long menuId);


}